# Author: Chris Moyer
# DB based session management
import time
import boto
import pickle

import marajo
from marajo.appengine.ext import db


import logging
log = logging.getLogger("marajo.webapp.session")


class Session(db.Expando):
    """
    Session object stored in the DB
    """
    __consistent__ = True
    start_time = db.DateTimeProperty(auto_now_add=True)

    def get(self, key, default=None):
        """
        Get attribute
        """
        if self.has_key(key):
            return self[key]
        else:
            return default

    def set(self, key, value):
        self[key] = value

    def __getitem__(self, key):
        try:
            return pickle.loads(str(self.__getattr__(key)))
        except:
            return self.__getattr__(key)

    def __setitem__(self, key, value):
        return self.__setattr__(key, pickle.dumps(value))

    def __delitem__(self, key):
        self._manager.delete_key_value(self, key)

    def has_key(self, key):
        try:
            val = getattr(self, key)
            return True
        except:
            return False


class S3Delegate(object):
    """
    Info was stored in S3 instead of SDB because it was too large
    """
    def __init__(self, sid, name, value=None):
        self.sid = sid
        self.name = name
        if value is not None:
            self.set(value)
    
    def get(self):
        s3 = boto.connect_s3()
        b = s3.get_bucket(marajo.config.get("session_bucket", "marajo_sessions"))
        k = b.get_key("%s/%s" % (self.sid, self.name))
        return k.get_contents_as_string()

    def set(self, value):
        s3 = boto.connect_s3()
        b = s3.get_bucket(marajo.config.get("session_bucket", "marajo_sessions"))
        k = b.get_key("%s/%s" % (self.sid, self.name))
        if k is None:
            k = b.new_key("%s/%s" % (self.sid, self.name))
        k.set_contents_from_string(value)

    def delete(self):
        s3 = boto.connect_s3()
        b = s3.get_bucket(marajo.config.get("session_bucket", "marajo_sessions"))
        k = b.get_key("%s/%s" % (self.sid, self.name))
        k.delete()
